package com.dlc.beijingrfid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.QueryRfidAdapter;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.net.bean.RFIDSpecListBean;
import com.dlc.beijingrfid.net.bean.StockCheckData;
import com.dlc.beijingrfid.net.protocol.StockProto;
import com.dlc.commonlibrary.ble.BleWorker;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.utils.RecyclerViewUtil;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018-01-28.
 */

public class QueryRfidActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.item_real_counting_amount)
    CommonItemView itemRealCountingAmount;//扫描到的所有RFID
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_read_rfid)
    Button mBtnReadRfid;

    private DoResultDialog doResultDialog, doReadDialog;

    private StringBuilder mStringBuilder;
    private ArrayList<String> RfList = new ArrayList<>();//扫描到的所有RFID
    private String startData = "";

    private QueryRfidAdapter mQueryRfidAdapter;

    private int exisNumber = 0;//存在仓库的数据
    private List<StockCheckData> mStockCheckList = new ArrayList<>();
    BleWorker mBleWorker = new BleWorker();

    @Override
    protected int getLayoutID() {
        return R.layout.activity_query_rfid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mTitleBar.leftExit(this);
        doReadRFID();
        InitRecyclerView();
        mBleWorker.setCallback(new BleWorker.ReadCallback() {
            @Override
            public void onReceiveData(ArrayList<String> rfList,int readNum) {

                RfList = rfList;
                doReadDialog.dismiss();
                itemRealCountingAmount.setContent(String.valueOf(RfList.size()));
                doReadDialog.showResultAndDismiss(true, 1000);
                if (RfList != null && RfList.size() > 0) {
                    getDataDetails(RfList);
                }
            }

            @Override
            public void onDeviceDisconnected() {
                doReadDialog.dismiss();
                Intent intent = new Intent(QueryRfidActivity.this,MainActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
                finish();
            }
            @Override
            public void onErrorNumber(int number) {
                if (number > 0) {
                    showOneToast("存在长度小于14的标签" + number + "个");
                }
            }
        });
    }

    @OnClick({R.id.btn_read_rfid})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_read_rfid:

                getData();
                break;
        }
    }
    private void InitRecyclerView(){
        mQueryRfidAdapter = new QueryRfidAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mQueryRfidAdapter.addHeaderView( LayoutInflater.from(QueryRfidActivity.this).inflate(R.layout.item_query_rfid, null, false));
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mQueryRfidAdapter);
    }
    private void doReadRFID() {
        doReadDialog =
            DoResultDialog.newDialog(this).
                setWorkingText(getString(R.string.read_rfid_ing))
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.scan_over))
                .setButton("完成扫描", new DoResultDialog.OnClickButtonListener() {
                    @Override
                    public void onClickButton(DoResultDialog dialog) {
                       mBleWorker.cancelCheck();
                    }
                });

        doReadDialog.setCancelable(false);

    }

    private void getData(){
        doReadDialog.showWorking(true);
        mBleWorker.check();
    }

    //private void doData(String data){
    //    rfidsList.add(data);
    //    LogPlus.e("蓝牙数据=" + data+"==蓝牙数据 count=" + rfidsList.size() + "");
    //}
    //
    //private Handler mHandler = new Handler() {
    //    @Override
    //    public void handleMessage(Message msg) {
    //    }
    //};
    //
    //private void judgeData() {
    //    runOnUiThread(new Runnable() {
    //        @Override
    //        public void run() {
    //            if (!isBleStop) {
    //                RfList.clear();
    //                if (rfidsList.size() > 0) {
    //                    if (rfidsList.size() == cashCount || TYPE == 2) {//获取到的缓存区数量相等或者是直接获取缓存数据
    //                        doReadDialog.dismiss();
    //                        for (String str : rfidsList) {
    //                            if (str.length() > 14) {
    //                                str = str.substring(str.length() - 12, str.length());
    //                                RfList.add(str);
    //                            }
    //                        }
    //                        itemRealCountingAmount.setContent(String.valueOf(RfList.size()));
    //                        getDataDetails(RfList);
    //                    } else {
    //                        //ToastUtil.show(getContext(),"获取的数量不对应，直接获取读到的缓存rfid");
    //                        TYPE = 2;
    //                        rfidsList.clear();
    //                        RRUA100API.getInstance(new Handler()).A100_getSyncTagList();
    //                    }
    //                }
    //            }else {
    //                showToast("未连接设备，跳到连接页面");
    //                Intent intent = new Intent(getActivity(),MainActivity.class);
    //                intent.putExtra("type", "2");
    //                startActivity(intent);
    //            }
    //        }
    //    });
    //
    //}



    private void getDataDetails(final List<String> dflist){
        StringBuilder sb = new StringBuilder();
        for(String rfid : dflist){
            sb.append(rfid+",");
        }
        String data = sb.substring(0,sb.length()-1);
        StockProto.get().rfid_spec(data)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RFIDSpecListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                }

                @Override
                public void onNext(RFIDSpecListBean dataBean) {
                    //mLaundryAdapter.setNewData(dataBean.data);
                    doStockData(dataBean);
                }
            });
    }

    private void doStockData(RFIDSpecListBean bean){
        mStockCheckList.clear();
        exisNumber = 0;
        if (bean.data!= null&&bean.data.size()>0) {
            for (int i = 0;i < bean.data.size();i++){
                StockCheckData data;
                if (TextUtils.isEmpty(bean.data.get(i).user)) {
                    data  =
                        new StockCheckData(bean.data.get(i).title, bean.data.get(i).count, "0", bean.data.get(i).hotel,
                            bean.data.get(i).office);
                }else {
                    data  =
                        new StockCheckData(bean.data.get(i).title, bean.data.get(i).count, "0", bean.data.get(i).hotel,
                            bean.data.get(i).office+"_"+bean.data.get(i).user);
                }
                exisNumber = exisNumber + Integer.parseInt(bean.data.get(i).count);
                mStockCheckList.add(data);
            }
        }

        //int otherNumber = RfList.size() - exisNumber;
        //if (otherNumber > 0){
        //    StockCheckData data = new StockCheckData("品名为空",String.valueOf(otherNumber),"0");
        //    mStockCheckList.add(data);
        //}
        mQueryRfidAdapter.setNewData(mStockCheckList);
    }
}
